package com.hyfrogx.modules.manage.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hyfrogx.common.param.VodStatus;
import com.hyfrogx.common.utils.QueryExt;
import com.hyfrogx.common.utils.R;
import com.hyfrogx.common.validator.ValidatorUtils;
import com.hyfrogx.modules.manage.entity.video.HyVideoVodEntity;
import com.hyfrogx.modules.manage.form.video.ConvertVodFileForm;
import com.hyfrogx.modules.manage.form.video.VideoVodVodDetailForm;
import com.hyfrogx.modules.manage.form.video.VideoVodUploadForm;
import com.hyfrogx.modules.manage.service.HyChannelApkService;
import com.hyfrogx.modules.manage.service.HyVideoVodService;
import com.hyfrogx.modules.sys.controller.AbstractController;
import com.hyfrogx.modules.sys.entity.SysUserEntity;
import io.swagger.annotations.Api;
import org.apache.http.Consts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/manage/vod")
@Api(value = "点播controller", tags = {"后台-点播视频"})
public class HyVideoVodController extends AbstractController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    HyVideoVodService hyVideoVodService;

    @Autowired
    HyChannelApkService hyChannelApkService;


    /**
     * 上传视频
     * @param form
     * @return
     */
    @PostMapping("/upload")
    public R uploadVod(@RequestBody VideoVodUploadForm form) {

        ValidatorUtils.validateEntity(form);
        SysUserEntity user = getUser();
        if (user == null) {
            return R.error("请先登录!");
        }
        int count = hyVideoVodService.isExistVideoBychannelId(form.getChannelId());
        if (count > 0) {
            return R.error("视频已经存在");
        }
        HyVideoVodEntity ent=new HyVideoVodEntity();
        ent.setStatus(VodStatus.WAIT_CONVERT.getCode());
        ent.setImg("1.jpg");
        ent.setUploadId(user.getUserId());
        ent.setUpdateDate(new Date());
        BeanUtil.copyProperties(form,ent);
        hyVideoVodService.getBaseMapper().insert(ent);
        return R.ok();
    }

    /**
     * 获取点播上传管理-资源列表 过滤条件包含:点播视频名/点播状态/类别/话题/片型
     * @param params
     * @return
     */
    @PostMapping("/list")
    public R getVodUpList(@RequestBody Map<String,Object> params) {
        return R.ok().put("data", hyVideoVodService.getVideoVodByConditions(new QueryExt(params)));
    }

    /**
     * 获取详情
     * @param id
     * @return
     */
    @PostMapping("/detail/{id}")
    public  R getDetailByFileId(@PathVariable Long id) {
        try {
            HyVideoVodEntity ent= hyVideoVodService.getBaseMapper().selectById(id);
            VideoVodVodDetailForm detail=new VideoVodVodDetailForm();
            BeanUtil.copyProperties(ent,detail);
            detail.setChannelList(hyChannelApkService.getChannelListByVodId(ent.getId()));
            //获取渠道号
            return R.ok().put("detail",detail);
        } catch (Exception e) {
            return R.ok(e.getMessage());
        }
    }

    /**
     * 视频转码操作
     * @param form
     * @return
     */
    @PostMapping("/convertVodFile")
    public R convertVodFile(@RequestBody ConvertVodFileForm form) {

        ValidatorUtils.validateEntity(form);
        try {
            hyVideoVodService.ConvertVodFile(form);
            return R.ok("操作成功");
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 获取签名接口
     */
    @PostMapping("/getSign")
    public R getSign(@RequestBody Map param) {
        try {
            Object result = hyVideoVodService.getSign(param);
            return R.ok().put("data",result);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }


    /**
     * web端获取视频信息,直接从腾讯云获取并返回
     * @param vodId
     * @return
     */
    @RequestMapping("/file/{vodId}")
    public  R getFileInfoByFileId(@PathVariable String vodId) {
        try {
            Object object = hyVideoVodService.getFileByFileId(vodId);
            return R.ok().put("data",object);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PostMapping(value = "/batchEdit/del")
    public R editSelectiveRadioAlbunProgram(String ids) {
        try {
            String[] idList=StrUtil.split(ids,",");
            for (int i = 0; i < idList.length; i++) {
                int result = hyVideoVodService.getBaseMapper().deleteById(Integer.parseInt(idList[i]));
                if (result < 0) {
                    return R.error("删除失败");
                }
            }
            return R.ok();
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * ** 批量下线、退回
     * @return
     */
    @PostMapping("/batchEdit/updateVodStatus")
    public R batchEditVodStatus(String ids, Integer status) {
        if (status.intValue() == VodStatus.EIDTED.getCode()) {
            return R.error("不能进行批量退回操作");
        }
        String[] idList=StrUtil.split(ids,",");
        HyVideoVodEntity vod =new HyVideoVodEntity();
        for (int i = 0; i < idList.length; i++) {
            vod.setId(Integer.parseInt(idList[i]));
            vod.setStatus(status);
            int result = hyVideoVodService.getBaseMapper().updateById(vod);
            if(result<0){
                return R.error("下线操作失败");
            }
        }
        return R.ok("下线操作成功");
    }


    /**
     * @author Li9527 该接口用于从点播服务端获取事件通知/普通回调,以配置实现。
     * @throws Exception
     */
    @PostMapping(value = "/getApiCallBack")
    public void getApiCallBack(HttpServletRequest request) throws Exception {
        InputStream is = request.getInputStream();
        StringBuffer stringBuffer = new StringBuffer();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, Consts.UTF_8));
        String line = "";
        while ((line = reader.readLine()) != null) {
            stringBuffer.append(line);
        }
        reader.close();
        // 获取request消息体
        String data = stringBuffer.toString();
        try {
            hyVideoVodService.callBack(data);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

}
